<?php
/**
 * Created by rcl
 * User: rcl
 * Date: 2017/2/21
 * Time: 14:35
 * 数字展厅贷款计算页面
 */

class Loan{

    public $userName = '';
    public $mobile = '';
    public $idCard = '';
    public $bankCard = '';
    public $conn = null;
    public $num = 10;

    public function __construct()
    {
        $data=json_decode(array_keys($_GET)[0],true);
        $this->userName=urlencode(htmlspecialchars(trim($data['userName'])));
        $this->mobile=urlencode(htmlspecialchars(trim($data['mobile'])));
        $this->idCard=urlencode(htmlspecialchars(trim($data['idCard'])));
        $this->bankCard=urlencode(htmlspecialchars(trim($data['bankCard'])));
    }

    /**
     * 银联接口请求方法
     */
    public function bankCurl()
    {
        $name = $this->userName;
        $phone = $this->mobile;
        $sfz = $this->idCard;
        $yhk = $this->bankCard;
        $lx=urlencode('身份证');
        $index='S0544';

        //curl 请求
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_PORT => "8243",
            CURLOPT_URL => "https://220.250.65.183:8243/data/ylzh_quota_usernature?card=".$yhk."&name=".$name."&identityType=".$lx."&identityCard=".$sfz."&mobile=".$phone."&index=".$index,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer db756ecebced3b5f6576220db03b13482a4f5d16",
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded;charset=UTF-8",
                "postman-token: 4dd255cd-e988-9080-25e9-93e39fea56bf"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return json_encode(["status"=>0,"msg"=>"查询异常"]);
        } else {
            return $response;
        }
    }

    /**
     * 综合接口请求
     */
    public function comCurl()
    {
        $curl = curl_init();
        $sfz = $this->idCard;
        $name = $this->userName;
        curl_setopt_array($curl, array(
            CURLOPT_PORT => "8243",
            CURLOPT_URL => "https://220.250.65.183:8243/data/P07011451077",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "name=".$name."&idcard=".$sfz,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer db756ecebced3b5f6576220db03b13482a4f5d16",
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded;charset=UTF-8"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return json_encode(["status"=>0,"statMsg"=>"查询异常"]);
        } else {
            return $response;
        }
    }

    /**
     * 执行接口查询的汇总
     */
    public function allCurl()
    {
        $str=$this->comCurl();
        $data=json_decode($str,'true');
        //检测overdueStatus和carStatus
        if (array_key_exists('status',$data)) {
            //表示查询失败
            return $str;
        }else {
            if ($data['rows']['overdueStatus']==0||$data['rows']['carStatus']==0) {
                return json_encode(['status'=>0,"statMsg"=>'查询信息已列入黑名单']);
            }else {
                //如果不在黑名单中的话，进行消费金额的查询
                $data=$this->bankCurl();
                return $data;
            }
        }

    }

    /**
     * 链接数据库
     * @param $db 要链接的数据库
     */
    public function connect($db){
        // $this->conf=Conf::getIns();
        $conn=mysqli_connect('localhost','pcm','pcm=pwd@2016');
        $res=mysqli_query($conn,"use $db");
        mysqli_query($conn,'set names utf8');
        $this->conn=$conn;
    }

    /**
     * @param $sql
     * @return bool|mysqli_result
     * 执行sql查询
     */
    public function query($sql){
        $rs=mysqli_query($this->conn,$sql);
        return $rs;
    }

    /**
     * @param $sql
     * @return array
     * 查询所有数据
     */
    public function getAll($sql){
        $rs=$this->query($sql);
        $data=array();
        while($row=mysqli_fetch_assoc($rs)){
            $data[]=$row;
        }
        return $data;
    }

    /**
     * @param $table
     * @param $data
     * @param string $act
     * @param int $where
     * @return bool|mysqli_result
     * 数据库插入语句
     */
    public function autoExecute($table,$data,$act='insert',$where=1){
        if(empty($data)){
            return false;
        }
        if($act=='insert'){
            //insert into table (a,b,c) values ('a','b','c');
            $sql="insert into $table (" . implode(',',array_keys($data)) . ") values ('";
            $sql .=implode("','",array_values($data)) . "')";
            return $this->query($sql);
        }else if($act=='update'){
            //update table set a='a',b='b' where id=1;
            $sql="update $table set ";
            foreach($data as $k=>$v){
                $sql .=$k . "='" . $v . "',";
            }
            $sql=rtrim($sql,',') . ' where ' .$where;
            // echo $sql;
            // exit;
            return $this->query($sql);
        }
    }

    /**
     * 调用接口，将今天热日期写入，同时将调用次数上加一
     */
    public function writeFile()
    {
        $str = file_get_contents('time_num.php');
        $arr = explode('#',$str);

        //比对今天时间和这个时间是否一样
        $time=date('Y-m-d',time());

        //如果记录中没有信息则执行写入首次的
        if ($str=='') {
            //对账号信息进行汇总查询
            $message = $this->allCurl();
            $arr_msg = json_decode($message,'true');
            if (array_key_exists('status',$arr_msg)) {
                //表示查询失败
                return $message;
            }else {
                file_put_contents('time_num.php',$time."#1");
                return $message;
            }
        } else {
            if ( $time == $arr[0] ) {
                $num=$arr[1];
                if ( $num>=$this->num ) {
                    return json_encode(['status'=>0,'statMsg'=>'今天查询次数已达上限']);
                }else {
                    //对账号信息进行汇总查询
                    $message = $this->allCurl();
                    $arr_msg = json_decode($message,'true');
                    if (array_key_exists('status',$arr_msg)) {
                        //表示查询失败
                        return $message;
                    }else {
                        $nums=$num+1;
                        //将文件今日日期和次数写入文件中
                        file_put_contents('time_num.php',$time."#".$nums);
                        return $message;
                    }
                }
            }else{
                $message = $this->allCurl();
                $arr_msg = json_decode($message,'true');
                if (array_key_exists('status',$arr_msg)) {
                    //表示查询失败
                    return $message;
                }else {
                    file_put_contents('time_num.php',$time."#1");
                    return $message;
                }
            }
        }

    }

    /**
     * 贷款计算方法
     * @param $money 查询到的用户的消费金额
     */
    public function finCount($money){
        $last_12_max = ($money*12*2)*1.2;
        $last_12_min = ($money*12*2)*0.8;
        $last_36_min = ($money*36*2)*0.8;
        $last_36_max = ($money*36*2)*1.2;

        $arr=[
            'status'=>1,
            'one_year'=>'12',
            'one_msg'=>($last_12_min/10000).'-'.($last_12_max/10000),
            'two_year'=>'36',
            'two_msg'=>($last_36_min/10000).'-'.($last_36_max/10000),
        ];
        return json_encode($arr);
    }

    /**
     * 查询此信息在数据库中是否存在，若存在则不查询，直接返回数据库中的值，否则继续
     */
    public function sqlGet(){
        $name = urldecode($this->userName);
        $mobile = urldecode($this->mobile);
        $idcard = urldecode($this->idCard);
        $bankcard = urldecode($this->bankCard);
        $this->connect('pcmdevinfo');
        //查询数据库中是否存在该顾客的数据
        $sql="select * from fintool where username = '" .$name . "' and mobile = '" . $mobile . "' and idcard = '" . $idcard . "' and bankcard = '" . $bankcard . "'";
        $data=$this->getAll($sql);
        $data[0]['status']='1';
        return json_encode($data[0]);
    }

    /**
     * 将查询到的信息写入数据库
     */
    public function writeSql($one_msg,$two_msg){
        $data=[];

        $name = urldecode($this->userName);
        $mobile = urldecode($this->mobile);
        $idcard = urldecode($this->idCard);
        $bankcard = urldecode($this->bankCard);

        //如果数据库中没有数据时候会执行到这一步，然后将查到的数据写入数据库
        $data['username'] = $name;
        $data['mobile'] = $mobile;
        $data['idcard'] = $idcard;
        $data['bankcard'] = $bankcard;
        $data['one_msg'] = $one_msg;
        $data['two_msg'] = $two_msg;

        $this->autoExecute('fintool',$data);
    }

    /**
     * 此功能业务逻辑执行方法
     */
    public function implement()
    {
        //先执行查询数据库，若无再继续操作
        $sqlData=$this->sqlGet();
        $sql_arr=json_decode($sqlData,'true');
        if (!array_key_exists('username',$sql_arr)) {
            $last_msg = $this->writeFile();
            $last_arr=json_decode($last_msg,'true');
            if (@$last_arr['status']=='0') {
                //表示查询失败
                return $last_msg;
            }else if(@$last_arr['resCode']=='0001'){
                $last_arr['statMsg']='没有查询到结果,无此卡号数据';
                return json_encode($last_arr);
            }else {
                //表示查询成功，使用计算金额方法
                $data = json_decode($last_msg,'true');
                $money = $data['data']['result']['S0544'];
                $last = $this->finCount($money);
                $last_arr = json_decode($last,'true');
                $this->writeSql($last_arr['one_msg'],$last_arr['two_msg']);
                return $last;
            }
        } else {
            return $sqlData;
        }


    }
}

$loan = new Loan();
$data=$loan->implement();
echo $data;
